package controller

import (
	context "context"
	v1 "kratos-realword/api/realworld/v1"
	"kratos-realword/internal/service"
)

type UserController struct {
	v1.UnimplementedUserServiceServer

	service *service.UserService
}

func NewUserController(service *service.UserService) *UserController {
	return &UserController{service: service}
}

func (controller *UserController) Login(ctx context.Context, req *v1.LoginRequest) (*v1.UserReply, error) {
	user, err := controller.service.Login(ctx, &service.UserLogin{Email: req.GetUser().Email, Password: req.GetUser().Password})
	if err != nil {
		return nil, err
	}
	return &v1.UserReply{User: &v1.User{
		Email:    user.Email,
		Token:    user.Token,
		Username: user.Username,
		Bio:      user.Bio,
		Image:    user.Image,
	}}, nil
}

func (controller *UserController) Register(ctx context.Context, req *v1.RegisterRequest) (*v1.UserReply, error) {
	userRegister := service.UserRegister{
		Username: req.GetUser().Username,
		Password: req.GetUser().Password,
		Email:    req.GetUser().Email,
	}
	user, err := controller.service.Register(ctx, &userRegister)
	if err != nil {
		return nil, err
	}
	return &v1.UserReply{User: &v1.User{
		Email:    user.Email,
		Username: user.Username,
		Token:    user.Token},
	}, nil
}

func (controller *UserController) GetCurrentUser(ctx context.Context, req *v1.GetCurrentUserRequest) (*v1.UserReply, error) {
	user, err := controller.service.GetCurrentUser(ctx)
	if err != nil {
		return nil, err
	}
	return &v1.UserReply{User: &v1.User{
		Email:    user.Email,
		Username: user.Username,
		Bio:      user.Bio,
		Image:    user.Image,
	}}, nil
}

func (controller *UserController) UpdateUser(ctx context.Context, req *v1.UpdateUserRequest) (*v1.UserReply, error) {
	return nil, nil
}
